package com.qidian.mes.controller;

import com.qidian.mes.pojo.Route;
import com.qidian.mes.service.RouteService;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;


@RestController
@RequestMapping("/route")
@CrossOrigin
public class RouteController {
    @Autowired
    private RouteService routeService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/list")
    public MESResult list(@RequestParam(defaultValue = "1")int page, @RequestParam(defaultValue = "10") int limit, Route route){
        return routeService.list(page,limit,route);
    }
    @PostMapping("/save")
    public MESResult save(@RequestBody Route route){
        return routeService.save(route);
    }

    @RequestMapping("/gen")
    public MESResult gen() {
        String key = "routeCode";
        // 生产编号的业务应该写在service中，我们这里因为时间关系，就直接写这里
        StringBuilder id = new StringBuilder();
        // 固定部分-可能需要从数据库查询
        id.append("R");
        // 时间
        Calendar calendar = Calendar.getInstance();
        id.append(calendar.get(Calendar.YEAR) + "" +
                (calendar.get(Calendar.MONTH) + 1) +
                calendar.get(Calendar.DATE));
        // 从redis获取序列

        Long idTemp = stringRedisTemplate.opsForValue().increment(key);
        String idStr = idTemp.toString();
        if(idStr.length() < 5){
         // 前面加0
            for (int i = 0;i < 5 - idStr.length();i++){
                idStr = "0" + idStr;
            }
        }
        id.append(idStr);
       return MESResult.ok(id);
    }
    @DeleteMapping("/delete")
    public MESResult delete(Long routeId){
        return routeService.delete(routeId);
    }

    @GetMapping("/get")
    public MESResult selectById(Long routeId){
        return routeService.selectById(routeId);
    }
    @PutMapping("/update")
    public MESResult update(@RequestBody Route route){
        return routeService.update(route);
    }
}
